package com.session.redis.queue;

import com.session.redis.entity.RedPacketMessage;
import org.redisson.Redisson;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

import java.util.concurrent.TimeUnit;

public class RedPacketDelayQueue {


    public static void main(String[] args) throws Exception {

        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer();
        serverConfig.setAddress("redis://127.0.0.1:6379");
        serverConfig.setPassword("123456");
        serverConfig.setDatabase(1);
        RedissonClient redissonClient = Redisson.create(config);
        /**
         * 红包目标队列
         */
        RBlockingQueue<RedPacketMessage> blockingRedPacketQueue
                = redissonClient.getBlockingQueue("redPacketDelayQueue");
        /**
         * 定时任务将到期的元素转移到目标队列
         */
        RDelayedQueue<RedPacketMessage> delayedRedPacketQueue
                = redissonClient.getDelayedQueue(blockingRedPacketQueue);

        /**
         * 延时信息入队列
         */
        // 经常会出现首条消息消费不了的情况，加一个初始为0的消息。
        delayedRedPacketQueue.offer(new RedPacketMessage(0), 1, TimeUnit.SECONDS);

        // 下面是真正的业务
        delayedRedPacketQueue.offer(new RedPacketMessage(5), 5, TimeUnit.SECONDS);
        delayedRedPacketQueue.offer(new RedPacketMessage(10), 10, TimeUnit.SECONDS);
        delayedRedPacketQueue.offer(new RedPacketMessage(30), 30, TimeUnit.SECONDS);
        delayedRedPacketQueue.offer(new RedPacketMessage(50), 50, TimeUnit.SECONDS);
        System.out.println("红包ID:");
        while (true){
            /**
             * 取出失效红包
             */
            RedPacketMessage redPacket = blockingRedPacketQueue.take();
            System.out.println("红包ID:" + redPacket.getRedPacketId() + "过期失效");
            /**
             * 处理相关业务逻辑：记录相关信息并退还剩余红包金额
             */
        }

    }
}
